package cc.linker.steplink.crm.task;

import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.dao.GroupDao;
import cc.linker.steplink.crm.merchant.service.PublicMenuService;
import cc.linker.steplink.crm.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分群人数统计
 *
 * @author wuyue
 */
@Slf4j
@Component
public class GroupStatistics {


    private GroupDao groupDao;

    private CustomerService customerService;

    @Autowired
    public GroupStatistics(GroupDao groupDao, CustomerService customerService) {
        this.groupDao = groupDao;
        this.customerService = customerService;
    }

    @RedisLock("GroupStatistics")
    @Scheduled(cron = "0 0 1 * * ?")
    public void doStatistics() {
        // 清空客户-分群关联表
        groupDao.delAll();
        // 获取所有分群
        List<Map<String, String>> allIncludes = groupDao.getAllIncludes();
        if (allIncludes != null && allIncludes.size() > 0) {
            for (Map<String, String> allInclude : allIncludes) {
                String groupId = allInclude.get("groupId");
                String include = allInclude.get("include");
                String orgId = allInclude.get("orgId");
                if (!StringUtils.isEmpty(groupId) && !StringUtils.isEmpty(include) && !StringUtils.isEmpty(orgId)) {
                    // 根据分群的include和orgId,查询所有符合规则的客户
                    List<String> strings = customerService.countGroup(include, orgId);
//                    if (strings != null && strings.size() > 0) {
                    int size = strings != null ? strings.size() : 0;
                    // 更新分群人数信息
                    Map<String, Object> map = new HashMap<>();
                    map.put("size", size);
                    map.put("groupId", groupId);
                    LOGGER.info("用户分群人数统计：group->" + groupId + ";include->" + include + ";size->" + size);
                    groupDao.updateGroupNum(map);
                    // 更新客户-分群关联表
                    if (strings != null && strings.size() > 0) {
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("customerId", strings);
                        map1.put("groupId", groupId);
                        groupDao.insertBatch(map1);
                    }
                }
            }
        }
    }

}
